<!-- 开发材料入库：蹇泽阳 -->
<template>
  <div class="app-container">
    <Find :OriginalFilter="{ static: true }" :formList="formList" @findClicked="findClicked" />
    <Find :searchImg="false" :OriginalFilter="{ static: true }" :formList="formList2" @findClicked="findClicked2" />
    <div class="flex mt10" style="width: 100%">
      <el-card shadow="never" :body-style="{ padding: '5px 10px 5px' }" style="width: 100%">
        <div class="flex">
          <h1 class="f16">开发材料入库</h1>
          <!-- <JDialog
            :tableHeader="JTableHeader"
            :width="73"
            @removeOne="removeOne"
            :currentTableRow="currentTableRow"
            @confirm="confirm"
            :unEdit="true"
            :unSub="true"
          /> -->
        </div>
        <Table
          :tableHeader="tableHeader"
          @selectList="selectTableList"
          :tableData="tableData"
          selection
          class="mt10"
          :isLoading="isLoading"
          @currentRow="currentRow"
        />
      </el-card>
    </div>
    <el-card shadow="never" :body-style="{ padding: '5px' }">
      <PageModule :PageData="{ total, buttonS: true }" @pageSizeChange="handleSizeChange" @pageChange="handleCurrentChange" />
    </el-card>

    <el-drawer v-model="drawerVisible" title="开发材料入库添加" :direction="'ttb'" size="small" :with-header="false">
      <Find :searchImg="false" :OriginalFilter="{ static: true }" :formList="formList3" @findClicked="findClicked3" />
      <Find :searchImg="false" :OriginalFilter="{ static: true }" :formList="formList4" @findClicked="findClicked4" />
      <span class="f12 mt10">双击入库数量默认填入订购数量</span>
      <Table
        selection
        @selectList="selectTableList2"
        :tableHeader="tableHeader2"
        :tableData="tableData2"
        class="mt10"
        :isLoading="isLoading2"
        @currentRow="currentRow2"
        @currentRow1="dbClickInput"
      />
      <PageModule :PageData="{ total: total2, buttonS: true }" @pageSizeChange="handleSizeChange2" @pageChange="handleCurrentChange2" />
    </el-drawer>
  </div>
</template>

<script lang="ts" setup name="DevelopmentMaterialsWarehoused">
import { ManufacturerQuery } from '@/api/PurchasingDepartment/FactoryPurchasing/MaterialRequisition'
import fileRequest from '@/utils/fileRequest'
import JMessage from '@/utils/JMessage'
import service from '@/utils/request'
import { debounce } from 'lodash'
import { watch } from 'vue'
import { onMounted } from 'vue'
import { ref } from 'vue'

const drawerVisible = ref(false)
const formList = ref([
  {
    type: 'input',
    inputPlaceholder: '请输入指令',
    inputValue: '',
    inputLabel: ''
  },
  {
    type: 'select',
    selectP: '请选择订单状态',
    selectValue: '',
    selectLabel: '',
    selectOptions: [
      {
        optionLabel: '已作废',
        optionValue: '-1',
        optionKey: '-1'
      },
      {
        optionLabel: '待入库',
        optionValue: '0',
        optionKey: '0'
      },
      {
        optionLabel: '已入库',
        optionValue: '1',
        optionKey: '1'
      }
    ]
  },
  {
    type: 'select',
    selectP: '请选择订单类型',
    selectValue: '',
    selectLabel: '',
    selectOptions: []
  },
  {
    type: 'input',
    inputPlaceholder: '请输入物料名称',
    inputValue: '',
    inputLabel: ''
  },
  {
    type: 'button',
    checkboxLabel: '置空',
    bgColor: '#1890FF'
  },
  {
    type: 'button',
    checkboxLabel: '入库批处理'
  },
  {
    type: 'button',
    checkboxLabel: '当前行入库单作废'
  },
  {
    type: 'button',
    checkboxLabel: '指令单下入库材料查询'
  },
  {
    type: 'button',
    checkboxLabel: '取消入库'
  },
  {
    type: 'button',
    checkboxLabel: '添加入库单'
  }
])
const formList3 = ref([
  {
    type: 'input',
    inputPlaceholder: '请输入指令',
    inputValue: '',
    inputLabel: ''
  },
  {
    type: 'input',
    inputPlaceholder: '请输入型体',
    inputValue: '',
    inputLabel: ''
  },
  {
    type: 'input',
    inputPlaceholder: '请输入订购单号',
    inputValue: '',
    inputLabel: ''
  },
  {
    type: 'input',
    inputPlaceholder: '请输入请购单号',
    inputValue: '',
    inputLabel: ''
  },
  {
    type: 'select',
    selectValue: '',
    selectP: '厂商',
    selectLabel: '',
    selectOptions: []
  },
  {
    type: 'date',
    dateLabel: '订购日期',
    dateValue: ''
  },
  {
    type: 'input',
    inputPlaceholder: '请输入采购员',
    inputValue: '',
    inputLabel: ''
  },
  {
    type: 'input',
    inputPlaceholder: '请输入物料ID',
    inputValue: '',
    inputLabel: ''
  },
  {
    type: 'input',
    inputPlaceholder: '请输入材料名称',
    inputValue: '',
    inputLabel: ''
  },
  {
    type: 'input',
    inputPlaceholder: '请输入材料颜色',
    inputValue: '',
    inputLabel: ''
  },
  {
    type: 'checkbox',
    checkboxLabel: '未下单',
    checked: true
  },
  {
    type: 'checkbox',
    checkboxLabel: '已下单',
    checked: true
  },
  {
    type: 'button',
    checkboxLabel: '置空'
  },
  {
    type: 'button',
    checkboxLabel: '查询'
  },
  {
    type: 'button',
    checkboxLabel: '导出当前行订购单'
  }
]) as any
const formList4 = ref([
  {
    type: 'select',
    selectValue: '',
    selectP: '请选择仓库',
    selectLabel: '',
    selectOptions: []
  },
  {
    type: 'select',
    selectP: '请选择订单类型',
    selectValue: '',
    selectLabel: '',
    selectOptions: []
  },
  {
    type: 'input',
    inputPlaceholder: '请输入送货单号',
    inputValue: '',
    inputLabel: ''
  },
  {
    type: 'dateSingle',
    dateLabel: '送货日期',
    dateValue: ''
  },
  {
    type: 'button',
    checkboxLabel: '置空'
  },
  {
    type: 'button',
    checkboxLabel: '打勾新增收货单'
  }
]) as any
// 表一模块
// 表一按钮
const findClicked = async (content: string) => {
  if (content === '置空') {
    formList.value.forEach((item: any) => {
      item.inputValue = ''
      item.selectValue = ''
      item.dateValue = ''
    })
  }
  if (content === '入库批处理') {
    if (selectedLists.value.length === 0) {
      JMessage.warning('请选择要入库的材料')
      return
    }
    const res = await service.post<any, any>(
      `/store/dev/receive`,
      selectedLists.value.map((item: any) => item.id)
    )
    if (res.code === 200) {
      JMessage.success('入库批处理成功')
      getTableList()
    } else {
      JMessage.error(res.msg)
    }
  }
  if (content === '当前行入库单作废') {
    const res = await service.post<any, any>(`/store/dev/receive/abandon/cansel?id=${currentTableRow.value.id}`)
    if (res.code === 200) {
      JMessage.success('入库单作废成功')
      getTableList()
    } else {
      JMessage.error(res.msg)
    }
  }
  if (content === '指令单下入库材料查询') {
    const res = await service.put<any, any>(
      `/store/dev/receive/list/mtlByLot?lotNo=${currentTableRow.value.lotNo}&orderType=${currentTableRow.value.orderType}`
    )
    if (res.code === 200) {
      JMessage.success('指令单下入库材料查询成功')
      getTableList()
    } else {
      JMessage.error(res.msg)
    }
  }
  if (content === '取消入库') {
    if (selectedLists.value.length === 0) {
      JMessage.warning('请选择要取消入库的材料')
      return
    }
    const res = await service.post<any, any>(
      `/store/dev/receive/unFinish`,
      selectedLists.value.map((item: any) => item.id)
    )
    if (res.code === 200) {
      JMessage.success('取消入库成功')
      getTableList()
    } else {
      JMessage.error(res.msg)
    }
  }
  if (content === '添加入库单') {
    drawerVisible.value = true
    getTableList2()
  }
}
const findClicked2 = async (content: string) => {
  if (content === '更新收货信息') {
    if (selectedLists.value.length === 0) {
      JMessage.warning('请选择要更新的材料')
      return
    }
    const res = await service.put<any, any>(
      `/store/dev/receive/sendMsgUp?sendNo=${
        formList2.value.find((item: any) => item.inputPlaceholder === '请输入送货单号')?.inputValue
      }&vendorName=${formList2.value.find((item: any) => item.selectP === '请选择厂商')?.selectValue}&remark=${
        formList2.value.find((item: any) => item.inputPlaceholder === '请输入备注')?.inputValue
      }`,
      selectedLists.value.map((item: any) => item.id)
    )
    if (res.code === 200) {
      JMessage.success('更新收货信息成功')
      getTableList()
    } else {
      JMessage.error(res.msg)
    }
  }
}
const findClicked4 = async (content: string) => {
  if (content === '置空') {
    formList4.value.forEach((item: any) => {
      item.inputValue = ''
      item.selectValue = ''
      item.dateValue = ''
    })
  }

  if (content === '打勾新增收货单') {
    if (formList4.value.find((item: any) => item.selectP === '请选择仓库')?.selectValue === '') {
      JMessage.warning('请选择仓库')
      return
    }
    if (formList4.value.find((item: any) => item.selectP === '请选择订单类型')?.selectValue === '') {
      JMessage.warning('请选择订单类型')
      return
    }
    if (formList4.value.find((item: any) => item.inputPlaceholder === '请输入送货单号')?.inputValue === '') {
      JMessage.warning('请输入送货单号')
      return
    }
    if (selectedLists2.value.length === 0) {
      JMessage.warning('请选择要新增的材料')
      return
    }
    if (selectedLists2.value.some((item: any) => item.acceptQty > item.purQty)) {
      JMessage.warning('入库数量不能大于订购数量')
      return
    }
    // 打勾新增收货单
    const res = await service.put<any, any>(
      '/store/dev/receive/add',
      selectedLists2.value.map((item: any) => {
        return {
          ...item,
          stkId: formList4.value.find((item: any) => item.selectP === '请选择仓库')?.selectValue,
          orderType: formList4.value.find((item: any) => item.selectP === '请选择订单类型')?.selectValue,
          sendNo: formList4.value.find((item: any) => item.inputPlaceholder === '请输入送货单号')?.inputValue,
          sendDate:
            formList4.value.find((item: any) => item.dateLabel === '送货日期')?.dateValue === ''
              ? currentDate()
              : formList4.value.find((item: any) => item.dateLabel === '送货日期')?.dateValue,
          lotNo: item.orderId,
          purId: item.id,
          id: '',
          orderStatus: 0
        }
      })
    )
    if (res.code === 200) {
      JMessage.success('打勾新增收货单成功')
      getTableList()
      getTableList2()
    } else {
      JMessage.error(res.msg)
    }
  }
}
// 日期
const currentDate = (date?: any) => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  let newMonth = month > 10 ? month : '0' + month
  let newDay = day > 10 ? day : '0' + day
  return `${year}-${newMonth}-${newDay}`
}
const tableData = ref([])
const isLoading = ref(true)
// 分页器
const currentPage = ref(1)
const pageSize = ref(40)
const total = ref(0)
const handleSizeChange = (val: number) => {
  pageSize.value = val
  getTableList()
}
const handleCurrentChange = (val: number) => {
  currentPage.value = val
  getTableList()
}

const tableHeader = ref([
  {
    label: '指令号',
    prop: 'lotNo'
  },
  {
    label: '厂商',
    prop: 'vendorName'
  },
  {
    label: '送货单号',
    prop: 'sendNo'
  },
  {
    label: '物料名称',
    prop: 'mtlName'
  },
  {
    label: '物料单位',
    prop: 'mtlUnit'
  },
  {
    label: '物料颜色',
    prop: 'mtlColor'
  },
  {
    label: '订单数量',
    prop: 'purQty'
  },
  {
    label: '仓库名称',
    prop: 'warehouseName'
  },
  {
    label: '库位',
    prop: 'address'
  },
  {
    label: '入库单号',
    prop: 'storeOrderNo'
  },
  {
    label: '实际数量',
    prop: 'acceptQty'
  },
  {
    label: '入库类型',
    prop: 'orderType'
  },
  {
    label: '入库状态',
    prop: 'orderStatus'
  },
  {
    label: '备注',
    prop: 'remark'
  }
])
// 获取表数据
const getTableList = debounce(async () => {
  isLoading.value = true
  let tableDataList = await service.post<any, any>('/store/dev/receive/list', {
    lotNo: formList.value.find((item: any) => item.inputPlaceholder === '请输入指令')?.inputValue,
    addr: formList.value.find((item: any) => item.selectP === '请选择仓库名称')?.selectValue,
    orderStatus: formList.value.find((item: any) => item.selectP === '请选择订单状态')?.selectValue,
    orderType: formList.value.find((item: any) => item.selectP === '请选择订单类型')?.selectValue,
    mtlName: formList.value.find((item: any) => item.inputPlaceholder === '请输入物料名称')?.inputValue,
    pageNum: currentPage.value,
    pageSize: pageSize.value
  })
  isLoading.value = false
  tableData.value = tableDataList.data.records.map((item: any) => {
    if (item.mtlBase) {
      item.mtlNo = item.mtlBase.mtlNo
      item.mtlName = item.mtlBase.mtlName
      item.mtlColor = item.mtlBase.mtlColor
      item.mtlUnit = item.mtlBase.mtlUnit
    }
    if (item.warehouse) {
      item.remark = item.warehouse.remark
      item.warehouseName = item.warehouse.warehouseName
      item.stkId = item.warehouse.stkId
      item.address = item.warehouse.address
    }
    return item
  })
  total.value = tableDataList.data.total
  currentRow()
}, 500)
onMounted(() => {
  getTableList()
})
watch(
  () =>
    formList.value.map((item: any) => {
      item.selectValue, item.inputValue, item.dateValue, item.checked
    }),
  () => {
    getTableList()
  }
)
// 点击表给另一张表传数据
const currentTableRow = ref({}) as any
const currentRow = async (row: any = tableData.value[0]) => {
  currentTableRow.value = row
}
const selectedLists = ref([]) as any
const selectTableList = (selectedList: any) => {
  selectedLists.value = selectedList
}

const getSelectList = async () => {
  // 获取仓库
  const storeList = (await service.get(`/store/warehouse/detail/back`)) as any
  if (storeList.code === 200) {
    formList4.value.find((item: any) => item.selectP === '请选择仓库')!.selectOptions = storeList.data.map((item: any) => ({
      optionKey: item.stkId,
      optionValue: item.stkId,
      optionLabel: `${item.warehouseName} - ${item.address}`,
      LeftLabel: `${item.warehouseName}`,
      RightLabel: `${item.address}`
    }))
    formList4.value.find((item: any) => item.selectP === '请选择仓库')!.selectValue = storeList.data[0].stkId
  }

  // 获取订单类型
  const res = await service.get<any, any>(`/store/OrderType/back?orderType=${1}`)
  if (res.code === 200) {
    formList.value.find((item: any) => item.selectP === '请选择订单类型')!.selectOptions = res.data.map((item: any) => ({
      optionLabel: item.typeName,
      optionValue: item.id,
      optionKey: item.id
    }))
    formList4.value.find((item: any) => item.selectP === '请选择订单类型')!.selectOptions = res.data.map((item: any) => ({
      optionLabel: item.typeName,
      optionValue: item.id,
      optionKey: item.id
    }))
    // 添加厂商
    let NewArray = []
    const result = await ManufacturerQuery()
    NewArray = result.rows.reduce((arr: any, item: any) => {
      if (item.vendorNo && item.vendorName) {
        // 只添加非空的 typeName 和 typeNo
        arr.push(item.vendorNo + '  ' + item.vendorName)
      }
      return arr
    }, [])
    formList3.value.find((item: any) => item.selectP === '厂商')!.selectOptions = NewArray.map((item: any) => {
      return {
        optionKey: item,
        optionValue: item,
        optionLabel: item
      }
    })
  }

  // 添加厂商
  let NewArray = []
  const result = await ManufacturerQuery()
  NewArray = result.rows.reduce((arr: any, item: any) => {
    if (item.vendorNo && item.vendorName) {
      // 只添加非空的 typeName 和 typeNo
      arr.push(item.vendorNo + '  ' + item.vendorName)
    }
    return arr
  }, [])
  formList2.value.find((item: any) => item.selectP === '请选择厂商')!.selectOptions = NewArray.map((item: any) => {
    return {
      optionKey: item,
      optionValue: item,
      optionLabel: item
    }
  })
}
onMounted(() => {
  getSelectList()
})

const JTableHeader = ref([
  {
    label: '指令号',
    prop: 'lotNo'
  },
  {
    label: '厂商',
    prop: 'vendorName'
  },
  {
    label: '送货单号',
    prop: 'sendNo'
  },
  {
    label: '订单数量',
    prop: 'orderQty'
  },
  {
    label: '仓库名称',
    prop: 'warehouseName'
  },
  {
    label: '入库单号',
    prop: 'storeOrderNo'
  },
  {
    label: '实际数量',
    prop: 'acceptQty'
  },
  {
    label: '入库类型',
    prop: 'orderType'
  },
  {
    type: 'selectJV2',
    label: '入库状态',
    prop: 'orderStatus',
    options: [
      {
        label: '已作废',
        value: '-1'
      },
      {
        label: '待入库',
        value: '0'
      },
      {
        label: '已入库',
        value: '1'
      }
    ]
  },
  {
    label: '备注',
    prop: 'remark'
  }
])

const formList2 = ref([
  {
    type: 'input',
    inputPlaceholder: '请输入送货单号',
    inputValue: ''
  },
  {
    type: 'select',
    selectP: '请选择厂商',
    selectValue: '',
    selectLabel: '',
    selectOptions: []
  },
  {
    type: 'input',
    inputPlaceholder: '请输入备注',
    inputValue: ''
  },
  {
    type: 'button',
    checkboxLabel: '更新收货信息'
  }
])

const tableData2 = ref([])
const isLoading2 = ref(true)
const tableHeader2 = ref([
  {
    label: '订单类型',
    prop: 'purType',
    change: true
  },
  {
    label: '指令号',
    prop: 'orderId',
    change: true
  },
  {
    label: '型体',
    prop: 'style',
    change: true
  },
  {
    label: '品牌',
    prop: 'brand',
    change: true
  },
  {
    label: '颜色',
    prop: 'color',
    change: true
  },
  {
    label: '材料颜色',
    prop: 'mtlColor',
    change: true
  },
  {
    label: '材料名称',
    prop: 'mtlName',
    change: true
  },
  {
    label: '规格',
    prop: 'mtlSpec',
    change: true
  },
  {
    label: '单位',
    prop: 'mtlUnit',
    change: true
  },
  {
    label: '订购单号',
    prop: 'purNo',
    change: true
  },
  {
    label: '订购日期',
    prop: 'purDate',
    change: true
  },
  {
    label: '订购数量',
    prop: 'purQty',
    change: true
  },
  {
    label: '入库数量',
    prop: 'acceptQty'
  },
  {
    label: '厂商名称',
    prop: 'vendorName',
    change: true
  },
  {
    change: true,
    label: '需求交期',
    prop: 'jqDate'
  },
  {
    label: '责任人',
    prop: 'dutyUser',
    change: true
  },
  {
    label: '责任原因',
    prop: 'dutyRek',
    change: true
  },
  {
    label: '采购人',
    prop: 'createBy',
    change: true
  },
  {
    label: '请购单号',
    prop: 'reqNo',
    change: true
  },
  {
    label: '请购时间',
    prop: 'reqDate',
    change: true
  },
  {
    label: '备注/订购备注',
    prop: 'remark',
    change: true
  }
])
const currentTableRow2 = ref({}) as any
const currentRow2 = async (row: any = tableData2.value[0]) => {
  currentTableRow2.value = row
}
const dbClickInput = (row: any) => {
  row.acceptQty = row.purQty
}
const currentPage2 = ref(1)
const pageSize2 = ref(40)
const handleSizeChange2 = (val: number) => {
  pageSize2.value = val
  getTableList2()
}
const handleCurrentChange2 = (val: number) => {
  currentPage2.value = val
  getTableList2()
}
// 表格计算函数
const cfmFlag10 = () => {
  const Unaudited = formList3.value.find((item: any) => item.type === 'checkbox' && item.checkboxLabel === '未下单')
  const Audited = formList3.value.find((item: any) => item.type === 'checkbox' && item.checkboxLabel === '已下单')
  if (!Unaudited || !Audited) return
  if (Unaudited.checked && Audited.checked) {
    return '0'
  } else if (Unaudited.checked) {
    return '1'
  } else if (Audited.checked) {
    return '2'
  } else {
    JMessage.warning('必须至少选择一项')
    Unaudited.checked = true
    Audited.checked = true
    return '0'
  }
}
const total2 = ref(0)
const getTableList2 = debounce(async () => {
  isLoading2.value = true
  let tableDataList2 = await service.post<any, any>('/mes/kf/commonOrder/getPcPurDetail', {
    lotNo: formList3.value.find((item: any) => item.inputPlaceholder === '请输入指令号')?.inputValue,
    style: formList3.value.find((item: any) => item.inputPlaceholder === '请输入型体')?.inputValue,
    purNo: formList3.value.find((item: any) => item.inputPlaceholder === '请输入订购单号')?.inputValue,
    reqNo: formList3.value.find((item: any) => item.inputPlaceholder === '请输入请购单号')?.inputValue,
    purType: formList3.value.find((item: any) => item.inputPlaceholder === '请输入订单类型')?.inputValue,
    vendorNo: formList3.value.find((item: any) => item.selectP === '厂商')?.selectValue.split(' ')[0],
    vendorName: formList3.value.find((item: any) => item.selectP === '厂商')?.selectValue.split(' ')[1],
    purDateStart: formList3.value.find((item: any) => item.dateLabel === '订购日期')?.dateValue[0],
    purDateEnd: formList3.value.find((item: any) => item.dateLabel === '订购日期')?.dateValue[1],
    mtlColor: formList3.value.find((item: any) => item.inputPlaceholder === '请输入材料颜色')?.inputValue,
    mtlName: formList3.value.find((item: any) => item.inputPlaceholder === '请输入材料名称')?.inputValue,
    purFlag: cfmFlag10(),
    userFlag: 2,
    purTypeFlag: 9,
    pageNum: currentPage2.value,
    pageSize: pageSize2.value
  })
  isLoading2.value = false
  tableData2.value = tableDataList2.rows.map((item: any) => {
    item.change = 'Y'
    item.disableConfirm = true
    return item
  })
  currentRow2()
  total2.value = tableDataList2.total
})
const selectedLists2 = ref([]) as any
const selectTableList2 = (selectedList: any) => {
  selectedLists2.value = selectedList
}
const findClicked3 = async (content: string) => {
  if (content === '置空') {
    formList3.value.forEach((item: any) => {
      item.inputValue = ''
      item.selectValue = ''
      item.dateValue = ''
      item.checked = false
    })
  }
  if (content === '查询') {
    getTableList2()
  }

  if (content === '导出当前行订购单') {
    // 导出当前行订购单
    if (!currentTableRow2.value.purNo) {
      JMessage.error('当前行订购单号不可为空')
      return
    }
    // 导出订购单
    const res = (await fileRequest.post(`/mes/kf/commonOrder/downMtlPurSlipExcel`, {
      purNo: currentTableRow2.value.purNo,
      purTypeFlag: 9
    })) as any
    const link = document.createElement('a') // 利用a标签自定义下载文件名
    let blob = new Blob([res.data]) // 创建Blob对象，设置文件类型
    link.style.display = 'none'
    //设置连接
    link.href = window.URL.createObjectURL(blob)
    const FileName = decodeURI(res.headers['content-disposition'].split(`filename=`)[1])
    link.download = FileName //自定义文件名字
    document.body.appendChild(link)
    //模拟点击事件
    link.click()
    document.body.removeChild(link)
  }
}
</script>
